package work

import (
	"fmt"
	"time"

	sadefine "gitee.com/simplexyz/simplego/actor/define"
)

func Post(rootContext *sadefine.RootContext, pid *sadefine.PID, work IPostWork) error {
	if work == nil {
		return ErrDoNotPostOrDispatchNilWork
	}

	p := CreateMessagePostWork(work)

	rootContext.Send(pid, p)

	return nil
}

func Dispatch(rootContext *sadefine.RootContext, pid *sadefine.PID, timeout time.Duration, work IDispatchWork) error {
	if work == nil {
		return ErrDoNotPostOrDispatchNilWork
	}

	if timeout <= 0 {
		timeout = DefaultDispatchTimeout
	}

	req := CreateMessageDispatchWork(work)

	f := rootContext.RequestFuture(pid, req, timeout)
	if e := f.Wait(); e != nil {
		return fmt.Errorf("wait dispatch result fail, %w", e)
	}

	r, err := f.Result()
	if err != nil {
		return fmt.Errorf("get dispatch result fail, %w", err)
	}

	resp, ok := r.(*MessageDispatchWork)
	if !ok || resp == nil {
		return ErrDispatchResultNotMatch
	}

	err = resp.Err

	DestroyMessageDispatchWork(resp)

	return err
}
